const Controller = require('@ppzp/controller')

const con = new Controller('/user')

con.get(function(ctx) {
  const id = ctx.getParams().id
  const data = id
    ? list.find(record => record.id == id)
    : list
  return {
    code: 0,
    data
  }
})

con.put(async function(ctx) {
  const record = await ctx.getJson()
  const index = list.findIndex(item => item.id == record?.id)
  if(index != -1) {
    Object.assign(list[index], record)
    return { code: 0 }
  } else
    return { code: 1 }
})

con.post(async function(ctx) {
  const record = await ctx.getJson()
  if(record.id)
    return { code: 2 }
  record.id = list[list.length - 1].id + 1
  list.push(record)
  return {
    code: 0,
    data: record.id
  }
})

con.delete(async function(ctx) {
  const id = ctx.getParams().id
  if(!id)
    return { code: 3 }
  const index = list.findIndex(record => record.id == id)
  if(index == -1)
    return { code: 4 }
  list.splice(index, 1)
  return { code: 0 }
})

var list = [
  {
    id: 1,
    name: 'ppz',
    phone: '110',
    gender: 'male'
  }, {
    id: 2,
    name: '小红',
    phone: '120',
    gender: 'female'
  }
]

module.exports = con